// pages/home/index.js
// import { dateFormat } from '../../utils/dateFormat.js'
import { submitDateFormat } from '../../utils/submitDateFormat.js'
import { decodeHTML } from '../../utils/decodeHTML.js'
import {dateFormat} from '../../utils/dateFormat.js'
const app = getApp()
wx.cloud.init({
  traceUser: true
})
const db = wx.cloud.database()
const user = db.collection('user')
const voice = db.collection('voice')
let clickLikeFlag = false

let refreshFlag = false
let touch = false
let topDistance = 45

let loadingFlag = false

let commentId = ''
let commentIndex
Component({
  options: {
    addGlobalClass: true,
  },
  properties: {
    isRefresh: {
      type: Boolean
    },
    homeNotification: {
      type: String,
      value: ''
    }
  },
  observers: {
    'isRefresh': function(isRefresh){
      if (isRefresh){
        this.getRecommend()
        this.setData({
          currentPage: 1,
          voiceList: []
        })
        this.getVoiceData(1)
      }
    }
  },
  /**
   * 页面的初始数据
   */
  data: {
    cardCur: 0,
    showNotification: true,
    focus: false,
    showCommentInput: false,

    loadingDown: false,
    loadingUp: false,
    scrollTop: -1,
    currentPage: 1,

    userOpenId: '',
    voiceList: [],
    isCard: false,
    setOpacity: false,
    swiperList: [],
    showDeleteModal: false,
    deleteVoiceId: ''
  },

methods: {
  hideNotification(){
    this.setData({
      showNotification: false
    })
  },
  lookHome(e) {
    wx.navigateTo({
      url: '/pages/personalHome/index?openid=' + e.currentTarget.dataset.openid,
    })
  },
  lookDetail(e) {
    if (e.currentTarget.dataset.voiceid == '') return
    wx.navigateTo({
      url: '/pages/detail/index?voiceid=' + e.currentTarget.dataset.voiceid,
    })
  },
  lookAllContent(e){
    let index = e.currentTarget.dataset.index
    // if (this.data.voiceList[index].voiceContent == this.data.voiceList[index].voiceContentAll) return
    wx.navigateTo({
      url: '/pages/detail/index',
      success:  (res) => {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          voice: this.data.voiceList[index]
          // allContent: this.data.voiceList[index].voiceContentAll,
          // bgImg: this.data.voiceList[index].coverImg
        })
      }
    })
  },
  upLoading(){ //上拉加载
    if (loadingFlag) return
    else loadingFlag = true
    if(this.data.voiceList.length == 0) return
    // console.log('到底了')
    this.data.currentPage++
    this.setData({
      currentPage: this.data.currentPage,
      loadingUp: true
    })
    this.getVoiceData(this.data.currentPage)
  },
  downRefresh(){
    if(refreshFlag) return
    else refreshFlag = true
    // setTimeout(() => {
    //   this.setData({
    //     scrollTop: 45
    //   })
    // }, 1000)
    
    // this.getVoiceData()
    // console.log('hehe')
    
  },
  writeComment(e){
    commentId = e.currentTarget.dataset.vid
    commentIndex = e.currentTarget.dataset.index
    this.setData({
      focus: true,
      showCommentInput: true
    })
  },
  handleBlur(e) {
    if(!e.detail.isSwitchEmoji){
      this.setData({
        showCommentInput: false
      })
    }
  },
  handleConfirm(e){
    if (e.detail.value.trim() == '') return
    this.data.voiceList[commentIndex].commentCount ++
    this.data.voiceList[commentIndex].commentInfo = {
      comment: e.detail.value,
      commentDate: dateFormat(new Date(), 'yyyy-MM-dd hh:mm'),
      reply: '',
      commnetatorInfo: {
        username: app.user.username,
        avatar: app.user.avatar
      }
    }
    this.setData({
      voiceList: this.data.voiceList,
      focus: false,
      showCommentInput: false
    })
    wx.cloud.callFunction({
      name: 'operateComment',
      data: {
        id: commentId,
        content: e.detail.value,
        state: 'comment'
      }
    })
  },
  lookImg(e){ //图片预览
    wx.previewImage({
      urls: [e.currentTarget.dataset.img],
      current: e.currentTarget.dataset.img
    })
  },
  getVoiceData(page){
    wx.cloud.callFunction({
      name: 'getVoice',
      data: {
        page
      }
    }).then(res => {
      if (res.result.length == 0){
        this.setData({
          loadingUp: false
        })
        return
      } 
      let list = []
      list = submitDateFormat(res.result)
      list.forEach((item, index) => {
        // this.data.voiceList[index].isLike = app.user.like.includes(item._id)
        // list[index].isLike = item.like.some(likeid => {
        //   if (likeid.likerOpenId == app.user._openid){
        //     return true
        //   }
        // })
        list[index].voiceContentAll = item.voiceContent
        list[index].voiceContent = decodeHTML(item.voiceContent)
        if(item.commentInfo){
          list[index].commentInfo.commentDate = dateFormat(item.commentInfo.commentDate, 'yyyy-MM-dd hh:mm')
          // list[index].commentInfo.commnetatorInfo = app.user
        }
      })
      // console.log(list)
      // console.log(this.data.voiceList)
      this.setData({
        voiceList: this.data.voiceList.concat(list),
        userOpenId: app.user._openid,
        loadingDown: false,
        loadingUp: false
      })
      if (page == 1){
        this.setData({
          // scrollTop: 45,
          setOpacity: false
        })
      }
      refreshFlag = false
      loadingFlag = false
      this.triggerEvent('setRefresh', false)
    }).catch(err => {
      console.log(err)
    })
  },
  deleteVoice(e){
    this.setData({
      showDeleteModal: true,
      deleteVoiceId: e.currentTarget.dataset.vid
    })
  },
  hideModal(){
    this.setData({
      showDeleteModal: false,
      deleteVoiceId: ''
    })
  },
  confirmDelete(){
    wx.showLoading({
      title: '删除中',
      mask: true,
    })
    wx.cloud.callFunction({
      name: 'deleteVoice',
      data: {
        voiceId: this.data.deleteVoiceId
      }
    }).then(res => {
      if (res.result == 1){
        this.setData({
          showDeleteModal: false
        })
        this.getRecommend()
        this.data.voiceList = this.data.voiceList.filter(item => {
          return item._id != this.data.deleteVoiceId
        })
        this.setData({
          deleteVoiceId: '',
          voiceList: this.data.voiceList
        })
        // this.getVoiceData(this.data.currentPage)
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 1000
        })
        app.sumCount = {}
      }
    }).catch(err => {
      console.log(err)
    })
  },
  makeLike(e){
    if (clickLikeFlag) return //点赞防抖处理
    else clickLikeFlag = true
    wx.vibrateShort()
    if (this.data.voiceList[e.currentTarget.dataset.index].isLike){
      this.data.voiceList[e.currentTarget.dataset.index].likeCount --
      wx.cloud.callFunction({
        name: 'operateLike',
        data: {
          id: this.data.voiceList[e.currentTarget.dataset.index]._id,
          state: 'cancel'
        }
      }).then(scs => {
        clickLikeFlag = false
      })
    }
    else{ //点赞
      this.data.voiceList[e.currentTarget.dataset.index].likeCount ++
      wx.cloud.callFunction({
        name: 'operateLike',
        data: {
          id: this.data.voiceList[e.currentTarget.dataset.index]._id,
          state: 'like'
        }
      }).then(scs => {
        // console.log('end')
        clickLikeFlag = false
      })
    }
    
    this.data.voiceList[e.currentTarget.dataset.index].isLike = !this.data.voiceList[e.currentTarget.dataset.index].isLike
    this.setData({
      voiceList: this.data.voiceList
    })
    app.sumCount = {}
  },
  DotStyle(e) {
    this.setData({
      DotStyle: e.detail.value
    })
  },
  // cardSwiper
  cardSwiper(e) {
    this.setData({
      cardCur: e.detail.current
    })
  },
  // towerSwiper
  // 初始化towerSwiper
  // towerSwiper(name) {
  //   let list = this.data[name];
  //   for (let i = 0; i < list.length; i++) {
  //     list[i].zIndex = parseInt(list.length / 2) + 1 - Math.abs(i - parseInt(list.length / 2))
  //     list[i].mLeft = i - parseInt(list.length / 2)
  //   }
  //   this.setData({
  //     swiperList: list
  //   })
  // },
  getRecommend(){
    wx.cloud.callFunction({
      name: 'getRecommend',
      data: {
        dataSize: 5
      }
    }).then(res => {
      this.setData({
        swiperList: res.result
      })
    }).catch(err => {
      console.log(err)
    })
  },
  handleScroll(e){
    // console.log(e.detail.scrollTop)
    topDistance = e.detail.scrollTop
    // console.log(touch)
    if (e.detail.scrollTop > 75){
      this.setData({
        setOpacity: true
      })
    } else{
      this.setData({
        setOpacity: false
      })
    }


  }
},
  
  /**
   * 生命周期函数--监听页面加载
   */
  created: function (options) {
    // this.towerSwiper('swiperList');
    this.getRecommend()
    this.getVoiceData(1)
  },
  
  attached: function(){
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})